package cn.wolfcode.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.wolfcode.domain.Question;
import cn.wolfcode.mapper.QuestionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IQuestionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;


    @Override
    public void save(Question question) {
        questionMapper.insert(question);
    }

    @Override
    public void delete(Long id) {
        questionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Question question) {
        questionMapper.updateByPrimaryKey(question);
    }

    @Override
    public Question get(Long id) {
        return questionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Question> listAll() {
        return questionMapper.selectAll();
    }

    @Override
    public PageInfo<Question> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Question> questions = questionMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Question>(questions);
    }

    @Override
    public void creatQuestion(Long examId,Integer singleChoice, Integer singleChoice_score, Integer multipleChoice, Integer multipleChoice_score, Integer judgeChoice, Integer judgeChoice_scroe) {
        Set<Long> singleChoiceId;
        Set<Long> multipleChoiceId;
        Set<Long> judgeChoiceId;
        if (singleChoice != null && singleChoice !=0){
            List<Long> id = questionMapper.selectAllType(1); // 拿到所有单选题的id
             singleChoiceId = RandomUtil.randomEleSet(id, singleChoice); //随机获取到所有单选题
            questionMapper.insertRelation(examId,singleChoiceId,singleChoice_score);

        }
        if (multipleChoice != null && multipleChoice !=0){
            List<Long> id = questionMapper.selectAllType(2); // 拿到所有单选题的id
            multipleChoiceId = RandomUtil.randomEleSet(id, singleChoice);
            questionMapper.insertRelation(examId,multipleChoiceId, multipleChoice_score);
        }
        if (judgeChoice != null && judgeChoice !=0){
            List<Long> id = questionMapper.selectAllType(3); // 拿到所有单选题的id
            judgeChoiceId = RandomUtil.randomEleSet(id, singleChoice);
            questionMapper.insertRelation(examId,judgeChoiceId, judgeChoice_scroe);
        }
    }
}
